package com.gblfy.qywxin.service;

import com.gblfy.qywxin.utils.UuidUtil;
import com.gblfy.qywxin.vo.FileVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class FileHandleService {


    public static final String WX_FILR_CATEGORY = "wx_pic";
    public static final Logger LOG = LoggerFactory.getLogger(FileHandleService.class);

    @Value("${file.path}")
    private String FILE_LOCAL_PATH;

    @Value("${file.domain}")
    private String FILE_PREVIEW_URL;

    public FileVo uploadChild(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String fileSize = String.valueOf(file.getSize());
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

        LOG.info("上传文件开始: {}");
        LOG.info("获取上传文件名称: {}", file.getOriginalFilename());
        LOG.info("上传文件大小: {}", fileSize);

        String key = UuidUtil.getShortUuid();

        //文件存储基础路径+分类目录
        File fileFullDir = new File(FILE_LOCAL_PATH + WX_FILR_CATEGORY);
        if (!fileFullDir.exists()) {
            fileFullDir.mkdirs();
        }
        //统一给文件添加前缀（随机生成9位id避免文件名称重复）
        String handleFileName = new StringBuffer(key)
                .append(".")
                .append(suffix)
                .toString();
        String path = new StringBuffer(File.separator)
                .append(handleFileName)
                .toString();

        // 保存文件到本地
        File dest = new File(fileFullDir + path);
        file.transferTo(dest);
        System.out.println("上传文件全路径: {}" + dest.getAbsolutePath());
        LOG.info("上传文件全路径: {}", dest.getAbsolutePath());


        FileVo fileVo = new FileVo();
        fileVo.setPicNumber(key);
        fileVo.setHandleFileName(handleFileName);
        fileVo.setFileBelongCategory(WX_FILR_CATEGORY);
        fileVo.setPreviewUrl(FILE_PREVIEW_URL + WX_FILR_CATEGORY + path);

        //保存文件到数据库
        //TODO

        return fileVo;
    }

    public void delSpeciFiedFile(String handleFileName, String fileBelongCategory, String picNumber) throws IOException {
        String delFilePath = FILE_LOCAL_PATH + File.separator + fileBelongCategory + File.separator + handleFileName;
        try {
            File file = new File(delFilePath);
            file.delete();

            // 根据picNumber主键删除数据库中的数据
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
